package com.example.com.skills_utf8;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.net.NetHelper;
import com.app.util.Utils;
import com.app.util.Utils_Data;
import com.app.view.ListViewInScroll;
import com.bean.Talk;
import com.bean.TalkMessage;
import com.bean.TalkMessageDB;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.umeng.message.PushAgent;
import com.utils.GsonParse;
import com.utils.g;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link _62Fragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link _62Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class _62Fragment extends android.support.v4.app.Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;


    PullToRefreshScrollView scrollview ;
    ListViewInScroll listview;

    Adapter adapter = new Adapter();
    List<Talk> listdata = new ArrayList<Talk>();


    Activity activity ;
    Handler handler = new Handler();


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment _62Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static _62Fragment newInstance(String param1, String param2) {
        _62Fragment fragment = new _62Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public _62Fragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }



    void initView(final Activity activity, View view){


        scrollview = (PullToRefreshScrollView)view.findViewById(R.id.scrollview);

        listview = (ListViewInScroll)view.findViewById(R.id.listview);
        listview.setAdapter(adapter);


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Talk talk = (Talk) parent.getItemAtPosition(position);

                Intent intent = new Intent(activity, _62_1Activity.class);
                intent.putExtra("bean", GsonParse.parse(talk));
                startActivity(intent);

            }
        });


        //
        // 显示dialog询问是否清空聊天记录
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                final Talk talk = (Talk)parent.getItemAtPosition(position);

                AlertDialog dialog = new AlertDialog.Builder(activity).setItems(new String[]{"清除聊天记录"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        try {
                            List<TalkMessageDB> all = ApplicationCustom.getInstance().db.findAll( Selector.from(TalkMessageDB.class).where("id_device", "=", talk.getId_umeng()) );
                            ApplicationCustom.getInstance().db.deleteAll(all);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                    }
                }).show();



                return false;
            }
        });


    }

    void initListener(){

        scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {


                requestNetDate_umengselect();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {

            }
        });
        scrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);



    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {




        activity = getActivity();
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment__62, container, false);


        initView(activity, view);
        initListener();


        requestNetDate_umengselect();



        return view;


    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }





    class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return listdata.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.layout_62, null);

            }

            Talk talk = listdata.get(position);
            TextView tv_nickname = (TextView)convertView.findViewById(R.id.tv_nickname);

            tv_nickname.setText( talk.getId_user() );


            return convertView;
        }
    }




    void requestNetDate_umengselect(){

        Utils.showLoadingDialog(activity, "", false);

        new NetHelper(activity){

            @Override
            public String init(ArrayList<BasicNameValuePair> arrayList) {
                String sign = g.token + g.id_umeng;

                arrayList.add( new BasicNameValuePair("id_device", g.id_umeng));
                arrayList.add( new BasicNameValuePair("sign", Utils_Data.MD5(sign)) );
                return g.SERVER_PAY_HOST + g.SERVER_PAY_API.select;
            }

            @Override
            public void onComplete(String s) throws JSONException {

                JSONObject obj = new JSONObject(s);
                JSONObject data = obj.getJSONObject("data");
                if(obj.getString("result").equals("0")){


                    listdata.clear();


                    JSONArray ids = data.getJSONArray("content");
                    for(int i =0; i<ids.length(); i++){
                        JSONObject o = ids.getJSONObject(i);
                        Talk talk = (Talk)GsonParse.parse(o.toString(), Talk.class);
                        listdata.add(talk);
                    }


                    /*
                    for(int i =0; i<20; i++){
                        Talk talk = new Talk();
                        talk.setId_user(""+i);
                        listdata.add(talk);
                    }
                    */

                    adapter.notifyDataSetChanged();
                }

            }

            @Override
            public void OnFinal() {
                super.OnFinal();

                scrollview.onRefreshComplete();
                Utils.dismissLoadingDialog();
            }
        }.start_GET();
    }



    public String getPhoneModel(){

        return android.os.Build.MODEL + ","
                + android.os.Build.VERSION.RELEASE;

    }


    // 如果刚买的手机，没有短信息,读彩信，读草稿箱，没有通话记录，读取sim卡信息
    // 工作量不小；
    public String getPhoneNO() {


        /*
        TelephonyManager tm = (TelephonyManager) activity .getSystemService(activity. TELEPHONY_SERVICE );
        System.out.println(tm.toString());
        if( tm.getLine1Number().isEmpty() == false )
            return tm.getLine1Number();
        */


        // http://blog.csdn.net/pi9nc/article/details/9320691
        // 始终得到的是对方的手机号码； 这里无法获得本机号码
        /*
        Uri sms = Uri.parse("content://sms");
        Uri mms = Uri.parse("content://mms");
        Uri sms_send = Uri.parse("content://sms/sent");

        ContentResolver cr = getContentResolver();
//        String[] projection = new String[] { "body" };//"_id", "address", "person",, "date", "type
        Cursor cur = cr.query(sms_send, null, null, null, null); //Cursor cur = cr.query(sms, null, null, null, "date desc");
        Cursor cur_mms = cr.query(mms, null, null, null, "date desc");

        if(cur != null){
            while (cur.moveToNext()) {
                String number = cur.getString(cur.getColumnIndex("address"));//手机号
                String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
                String body = cur.getString(cur.getColumnIndex("body"));
                String type = cur.getString(cur.getColumnIndex("type"));


                // 始终得到的是对方的号码
                if( type.equals("2") && number.isEmpty() == false)
                     return number;
            }

        }
        else if(cur_mms.moveToFirst()){

            while(cur_mms.moveToNext()){

                String creator = cur_mms.getString( cur_mms.getColumnIndex(Telephony.BaseMmsColumns.CREATOR) );
                System.out.println(creator);



            }

        }
        */

        return "";

    }






}
